#include <iostream>

#include <boost/asio.hpp>
#include <boost/bind.hpp>

#include "Server.hpp"

Server::Server(boost::asio::io_service &io_service, boost::asio::ip::tcp::endpoint endpoint)
	: acceptor(io_service, endpoint), socket(io_service)
{
	Accept();
}

void Server::Accept()
{
	std::cout << "Waiting for a new connection.." << std::endl;
	acceptor.async_accept(socket, boost::bind(&Server::AcceptHandler, this, boost::asio::placeholders::error));
}

void Server::AcceptHandler(const boost::system::error_code &error)
{
	if (!error)
	{
		std::cout << "New connection accepted ( " << socket.remote_endpoint().address().to_string() << ":" << socket.remote_endpoint().port() << " )" << std::endl;
		std::make_shared<Session>(std::move(socket))->Begin();
	}
	else
	{
		socket.close();
	}

	Accept();
}